package com.io.smartappframe.mvp.ui.activity

import android.graphics.Rect
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.io.base.mvp.BaseActivity
import com.io.commonlib.helper.CommonDeviceHelper
import com.io.commonlib.helper.DensityHelper
import com.io.commonlib.helper.LogHelper
import com.io.commonlib.helper.ToastHelper
import com.io.smartappframe.R
import com.io.smartappframe.databinding.ActivityRefreshRecyclerViewBinding
import com.io.smartappframe.mvp.contract.RefreshRecyclerViewContract
import com.io.smartappframe.mvp.model.entity.Friend
import com.io.smartappframe.mvp.presenter.RefreshRecyclerViewPresenter
import com.io.smartappframe.mvp.ui.adapter.RefreshRecyclerViewAdapter
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener

/**
 * Description:带刷新功能的列表
 * 2021-03-20 9:46
 * @author LiuMin
 */
class RefreshRecyclerViewActivity :
    BaseActivity<RefreshRecyclerViewPresenter, ActivityRefreshRecyclerViewBinding>(),
    RefreshRecyclerViewContract.IMainView, OnRefreshListener, OnLoadMoreListener,
    View.OnClickListener {
    private lateinit var list: MutableList<Friend>
    private lateinit var adapter: RefreshRecyclerViewAdapter
    private val DATA_LENGTH = 10
    private var START_INDEX = 0
    override fun initView(savedInstanceState: Bundle?): ActivityRefreshRecyclerViewBinding {
        return ActivityRefreshRecyclerViewBinding.inflate(layoutInflater)
    }

    override fun initData(savedInstanceState: Bundle?) {
        mViewBinding.header.tvTitle.setText("带刷新功能的列表")
        mViewBinding.header.ivToolbarBack.setOnClickListener(this)
        mPresenter = RefreshRecyclerViewPresenter(this)
        initRecyclerView()
        correctRecyclerview()
        mPresenter?.getList(START_INDEX, DATA_LENGTH)
    }

    override fun showSuccess(friendList: MutableList<Friend>?) {
        LogHelper.d(TAG, "showSuccess----------------${list.size}")
        friendList?.let {
            if (list.size > 0) {
                list.addAll(friendList)
                adapter.append(friendList)
            } else {
                list.addAll(friendList)
                adapter.notifyData(list)
            }
        }
    }

    override fun showFail(msg: String) {
        ToastHelper.showShortToast(applicationContext, msg)
    }

    private fun initRecyclerView() {
        list = ArrayList()
        adapter = RefreshRecyclerViewAdapter()
        val layoutManager = LinearLayoutManager(this)
        mViewBinding.recyclerView.layoutManager = layoutManager
        mViewBinding.recyclerView.adapter = adapter
        initFreshLayout()
    }

    /**
     * 初始化SmartRefreshLayout
     */
    private fun initFreshLayout() {
        mViewBinding.refreshLayout.setRefreshHeader(ClassicsHeader(this))
        mViewBinding.refreshLayout.setRefreshFooter(ClassicsFooter(this))
        mViewBinding.refreshLayout.setOnRefreshListener(this)
        mViewBinding.refreshLayout.setOnLoadMoreListener(this)
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        LogHelper.d(TAG, "onRefresh-----------------------")
        list = ArrayList()
        START_INDEX = 0
        mPresenter?.getList(START_INDEX, DATA_LENGTH)
        mViewBinding.refreshLayout.finishRefresh(200)
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        START_INDEX += DATA_LENGTH
        LogHelper.d(TAG, "onLoadMore--" + START_INDEX)
        mPresenter?.getList(START_INDEX, DATA_LENGTH)
        mViewBinding.refreshLayout.finishLoadMore(100)
    }
    override fun onClick(v: View?) {
        v?.let {
            if(it.id == R.id.iv_toolbar_back){
                finish()
            }
        }
    }

    /**
     * 纠正recyclerview在键盘弹出遮挡输入框的问题
     */
    private fun correctRecyclerview() {
        window.decorView.viewTreeObserver.addOnGlobalLayoutListener {
            // 除了软键盘以外的可见区域
            val rect = Rect()
            window.decorView.getWindowVisibleDisplayFrame(rect)
            // 计算出剩余高度：  除了状态栏高度、topBar高度、bottomBar高度、键盘高度的剩余高度
            val invisibleHeight = (rect.bottom
                    - CommonDeviceHelper().getStatusBarHeight(this)
                    - DensityHelper.dp2px(this, 44F))

            // 计算出所点击的图片描述的EditText距离RecyclerView顶部的距离
            val etDescView  =
                mViewBinding.recyclerView.getLayoutManager()?.findViewByPosition(adapter.currentFocusIndex)
            etDescView?.let {
                val focusViewTop = etDescView.top
                val itemHeight = etDescView.height
                val differ = focusViewTop + itemHeight - invisibleHeight
                if (differ > 0) {
                    // 让RecyclerView滚动差的那点距离
                    mViewBinding.recyclerView.scrollBy(0, differ)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ToastHelper.cancelToast()
    }
}